package com.liuliu.controller.system;

import com.liuliu.common.constant.Constants;
import com.liuliu.common.core.domain.AjaxResult;
import com.liuliu.common.core.domain.entity.SysMenu;
import com.liuliu.common.core.domain.entity.SysUser;
import com.liuliu.common.core.domain.model.LoginBody;
import com.liuliu.common.core.domain.model.LoginUser;
import com.liuliu.common.utils.ServletUtils;
import com.liuliu.framework.web.service.SysLoginService;
import com.liuliu.framework.web.service.SysPermissionService;
import com.liuliu.framework.web.service.TokenService;
import com.liuliu.system.service.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

/**
 * @descripttion:登录验证
 * @Author: WZH
 * @Date :2021/3/16  11:49
 **/
@RestController
@SuppressWarnings("all")
public class SysLoginController {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private SysLoginService loginService;
    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private ISysMenuService menuService;
    /**
     * 登录方法
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody  LoginBody loginBody){
        AjaxResult ajaxResult = AjaxResult.success();
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajaxResult.put(Constants.TOKEN,token);
        return ajaxResult;
    }
    /**
     * 获取用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo(){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        Set<String> rolePermission = permissionService.getRolePermission(user);
        Set<String> menuPermission = permissionService.getMenuPermission(user);
        AjaxResult success = AjaxResult.success();
        success.put("user",user);
        success.put("roles",rolePermission);
        success.put("permissions",menuPermission);
        return success;

    }
    /**
     * 获取路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouter(){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        List<SysMenu> sysMenus = menuService.selectMenuTreeByUserId(user.getUserId());
        return AjaxResult.success(menuService.buildMenus(sysMenus));
    }
}
